package com.service;

import com.entity.Commodity;
import com.entity.Orders;
import com.mapper.CommodityMapper;
import com.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  订单管理服务类
 * </p>
 *
 * @author hlt
 * @since 2021-03-06
 */
@Service
@Transactional
public class OrdersService {
    @Autowired
    OrdersMapper orderMapper;

    @Autowired
    CommodityMapper commodityMapper;


    public void InsertOrder(Orders order){
        orderMapper.InsertOrder(order);
    }
    public Orders LookOrderDetail(String ordernumber){
        return orderMapper.LookOrderDetail(ordernumber);
    }
    public void ChangeOrder(Orders orders){
        orderMapper.ChangeOrder(orders);
    }

    /**分页展示个人的订单记录*/
    public List<Orders> queryAllOrderecord(Integer page, Integer count, String buyuserid){
        return orderMapper.queryAllOrderecord(page,count,buyuserid);
    }
    /**查看订单记录总数*/
    public Integer queryOrderCount(String buyuserid){
        return orderMapper.queryOrderCount(buyuserid);
    }

    /**分页展示个人的售出记录*/
    public List<Orders> queryAllSoldrecord(Integer page, Integer count, String selluserid){
        return orderMapper.queryAllSoldrecord(page,count,selluserid);
    }
    /**查看售出记录总数*/
    public Integer querySoldCount(String selluserid){
        return orderMapper.querySoldCount(selluserid);
    }

    /**
     * 统计现有所有商品销量
     * @param userid
     * @return
     */
    public List<Map<String, Object>> queryOrderBySelluserid(String userid) {
        List<Orders> orders = orderMapper.queryOrderBySelluserid(userid);

        // 按照商品ID分组并汇总销量
        Map<String, Integer> productSales = orders.stream()
                .collect(Collectors.groupingBy(Orders::getCommid,
                        Collectors.summingInt(Orders::getCommnumber)));

        // 创建一个映射以获取商品名称（这里为了简单起见，我们直接用商品ID关联商品名称）
        Map<String, String> productNameMap = orders.stream()
                .collect(Collectors.toMap(Orders::getCommid, Orders::getCommname, (existing, replacement) -> existing));

        // 将汇总结果转换为目标格式
        List<Map<String, Object>> result = productSales.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("value", entry.getValue());
                    map.put("name", productNameMap.getOrDefault(entry.getKey(), "Unknown"));
                    return map;
                })
                .collect(Collectors.toList());

        return result;
    }
}
